import { type reference } from "../types/message";

// 可配置的图片服务基础 URL
const IMAGE_BASE_URL =
  import.meta.env.VITE_IMAGE_BASE_URL || "http://localhost/v1/document/image";

export function replaceId(
  originalString: string,
  referenceData: reference[] = []
): string {
  // 合并两个正则,使用可选的句号匹配
  const regex = /\[ID:(\d+)\](。)?/g;

  return originalString.replace(regex, (match, idNumber) => {
    const index = Number(idNumber) - 1;

    // 边界检查
    if (index < 0 || index >= referenceData.length) {
      return "";
    }

    const data = referenceData[index];
    const imageId = data?.image_id;

    // 如果有图片 ID,返回 Markdown 图片语法;否则返回引用标记
    return imageId ? `![](${IMAGE_BASE_URL}/${imageId})` : `®[${idNumber}]`;
  });
}

export function replaceQuote(
  originalString: string,
  referenceData: reference[] = []
): string {
  const regex = /®\[(\d+)\]/g;
  return originalString.replace(regex, (match, idNumber) => {
    const data: reference = referenceData[idNumber - 1];
    const documentContent = data?.content || "";
    const documentKeyword = data?.document_keyword || "";
    if (documentKeyword) {
      // 转义 HTML 内容以避免 XSS
      const escapedKeyword = documentKeyword
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
      const escapedContent = documentContent
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");

      return `<div class="reference-mark">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
          <polyline points="14 2 14 8 20 8"></polyline>
        </svg>
        <span class="reference-tooltip">
          <div class="tooltip-title">${escapedKeyword}</div>
          <div class="tooltip-content">${escapedContent}</div>
        </span>
      </div>`;
    }
    return "";
  });
}
